# @Author  : jmchen13
# @Time    : 2023/8/3 17:29
# @File    : selenium_script.py

"""
Chrome版本: 115.0.5790.171
Chrome Driver版本: win32 115.0.5790.110
selenium版本: 4.8.0
"""

import os

from selenium import webdriver
from selenium.common import ElementNotVisibleException, ElementNotSelectableException
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 文件存放的目录
CURRENT_PATH = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'download'
print("Download path:", CURRENT_PATH)

TIME_OUT = 180
print("TIME_OUT:", TIME_OUT)

# 创建 Chrome 浏览器的选项对象
chrome_options = Options()
chrome_options.add_experimental_option("prefs", {
    "download.default_directory": CURRENT_PATH,  # 默认下载路径
    "profile.default_content_settings.popups": 1,  # 设置为0禁止弹出窗口
})

# 创建 Chrome 浏览器对象
driver = webdriver.Chrome(
                          options=chrome_options)

wait = WebDriverWait(driver, timeout=TIME_OUT, poll_frequency=2,
                     ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException])

# 访问网页
driver.get("https://www.sobot.com/console/login")

# 登录
user_input = wait.until(
    EC.presence_of_element_located((By.XPATH,
                                    "/html/body/div[1]/div/div[3]/div[1]/div/form/div[3]/input")))
passwd_input = wait.until(
    EC.presence_of_element_located((
        By.XPATH,
        "/html/body/div[1]/div/div[3]/div[1]/div/form/div[4]/input"
    )))

login_button = wait.until(
    EC.presence_of_element_located((
        By.XPATH,
        "/html/body/div[1]/div/div[3]/div[1]/div/form/button"
    ))
)
user_input.send_keys("songli2@iflytek.com")
passwd_input.send_keys("daydayup1")
login_button.click()

# 在线客服
zxkf_button = wait.until(
    EC.presence_of_element_located((
        By.XPATH,
        "/html/body/div/div/div[2]/div[2]/div[1]/div/div/div/div/div/div/div/div[2]/div[2]/div/div/div[1]/a"
    ))
)
zxkf_button.click()

# 会话记录
hhjl_button = wait.until(
    EC.presence_of_element_located((
        By.XPATH,
        "/html/body/div[1]/div/div[2]/div[2]/div[1]/div/div/div/div/div/div[1]/div[2]/ul/li[3]/ul/li["
        "1]/span/a"
    ))
)
hhjl_button.click()

# 点击日历
calendar_button = wait.until(
    EC.presence_of_element_located((
        By.XPATH,
        "/html/body/div[1]/div/div[2]/div[2]/div[1]/div/div/div/div/div/div[2]/div/div/div/div/div["
        "2]/div[1]/div[1]/div/div[2]/div/div/div"
    ))
)
calendar_button.click()

# 选择最近30天
last_30d_button = wait.until(
    EC.presence_of_element_located((
        By.XPATH,
        "/html/body/div[1]/div/div[2]/div[2]/div[1]/div/div/div/div/div/div[2]/div/div/div/div/div["
        "2]/div[1]/div[1]/div/div[2]/div/div/div/div[5]/div/div/div/div[2]/div[2]/ul/li[10]/span"
    ))
)
last_30d_button.click()

time.sleep(1)

# 点击查询
query_button = wait.until(
    EC.presence_of_element_located((
        By.XPATH,
        "/html/body/div[1]/div/div[2]/div[2]/div[1]/div/div/div/div/div/div[2]/div/div/div/div/div["
        "2]/div[1]/div[1]/div/div[9]/div/div/div[2]/button/span"
    ))
)
query_button.click()


def blocking_wait_for_query(time_out):
    query_table = driver.find_element(By.XPATH,
                                      "/html/body/div[1]/div/div[2]/div[2]/div[1]/div/div/div/div/div/div["
                                      "2]/div/div/div/div/div[2]/div[2]/div[1]/div/div/div/div/div[2]/table/tbody")
    table_tr_list = query_table.find_elements(By.TAG_NAME, "tr")
    num_rows = len(table_tr_list)
    start = int(time.time())
    # 表格行数发生变化，说明查询结果返回
    while True:
        query_table = driver.find_element(By.XPATH,
                                          "/html/body/div[1]/div/div[2]/div[2]/div[1]/div/div/div/div/div/div["
                                          "2]/div/div/div/div/div[2]/div[2]/div[1]/div/div/div/div/div[2]/table/tbody")
        table_tr_list = query_table.find_elements(By.TAG_NAME, "tr")

        if len(table_tr_list) > num_rows:
            return True
        curr = int(time.time())
        if curr - start > time_out:
            return False


run = blocking_wait_for_query(TIME_OUT)


if run:
    # 点击导出
    export_button = wait.until(
        EC.presence_of_element_located((
            By.XPATH,
            "/html/body/div[1]/div/div[2]/div[2]/div[1]/div/div/div/div/div/div[2]/div/div/div/div/div[2]/div[1]/div["
            "2]/div/div[2]/div/button"
        ))
    )
    export_button.click()

    # 点击下载文件
    download_button = wait.until(
        EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div/div[2]/div/div[2]/div[3]/div/button")))
    download_button.click()


    def every_downloads_chrome(driver):
        if not driver.current_url.startswith("chrome://downloads"):
            driver.get("chrome://downloads/")
        return driver.execute_script("""
            var items = document.querySelector('downloads-manager')
                .shadowRoot.getElementById('downloadsList').items;
            if (items.every(e => e.state === "COMPLETE"))
                return items.map(e => e.fileUrl || e.file_url);
            """)


    # 等待文件下载完成并返回路径
    paths = WebDriverWait(driver, 120, 1).until(every_downloads_chrome)
    print("文件获取成功!")
    print(paths)
else:
    print("文件获取失败!")
# 关闭浏览器
driver.quit()
